﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;

namespace ERP.WebUI.Controllers
{
    public class LoginController : Controller
    {
        UserRepository _userRepository = new UserRepository();
        // GET: /Login/
        //实现用户的登录
        public ActionResult Index()
        {
            return View();
        }
        //判断用户输入的信息是否正确
        [HttpPost]
        public ActionResult CheckUserInfo(User user, string Code)
        {
            //首先我们拿到系统的验证码
            string sessionCode = this.TempData["ValidateCode"] == null
                                     ? new Guid().ToString()
                                     : this.TempData["ValidateCode"].ToString();
            //然后我们就将验证码去掉，避免了暴力破解
            this.TempData["ValidateCode"] = new Guid();
            //判断用户输入的验证码是否正确
            if (sessionCode != Code)
            {
                return Content("验证码输入错误");
            }

            string loginPwd = DESProvider.EncryptString(user.LoginPwd);
            //校验用户是否正确
            Expression<Func<User, Boolean>> expr = t => t.LoginName.Equals(user.LoginName) && t.LoginPwd.Equals(loginPwd) && t.IsDeleted == false;
            var loginUserInfo = _userRepository.CheckUserLogin(expr);
            if (loginUserInfo != null)
            {
                if (loginUserInfo.Enabled == false)
                {
                    return Content("你的账户已经被禁用");
                }
                else
                {
                    SessionHelper.SetSession("CurrentUser", loginUserInfo);
                    return Content("OK");
                }
            }
            else
            {
                return Content("用户密码错误");
            }
        }

        public ActionResult SignOut()
        {
            SessionHelper.Del("CurrentUser");
            return RedirectToAction("Index");
        }


        /// <summary>
        /// 验证码的实现
        /// </summary>
        /// <returns></returns>
        public ActionResult CheckCode()
        {
            //首先实例化验证码的类
            ValidateCode validateCode = new ValidateCode();
            //生成验证码指定的长度
            string code = validateCode.CreateValidateCode(4);
            //将验证码赋值给Session变量
            //Session["ValidateCode"] = code;
            this.TempData["ValidateCode"] = code;
            //创建验证码的图片
            byte[] bytes = validateCode.CreateValidateGraphic(code);
            //最后将验证码返回
            return File(bytes, @"image/jpeg");
        }
    }
}
